<template>
  <div>
    <el-tooltip :open-delay="1000"
                :content="datasetNameTooltip"
                :disabled="(!datasetNameTooltip||datasetNameTooltip===''||datasetNameTooltip===null) || value.length === 0"
                placement="top">
      <ExpandCascader v-model="value"
                      :options="options"
                      :style="width"
                      popper-class="dataset_data_grounp_cascader"
                      :props="{ expandTrigger: 'hover', virtual: true }"
                      v-loading='datasetSelectLoading'
                      :placeholder="placeholder"
                      clearable
                      @change="onSelectChange"
                      @clear="onSelectChange"
                      :filter-method="filterMethod"
                      filterable
                      :disabled='disabled||datasetSelectLoading'>
        <template v-slot="{data}">
          <span v-if="!data.datasetStatus">
            {{data.label}}
          </span>
          <CascaderNode :data="data"
                        :widthLength="widthLength"
                        :props="{status:'datasetStatus'}"
                        :type="type"
                        v-else />
        </template>

        <template v-slot:suggestion="{node,data}">
          <span v-if="!data.datasetStatus">
            {{node.text}}
          </span>
          <CascaderNode :data="data"
                        :widthLength="widthLength"
                        :props="{status:'datasetStatus'}"
                        :type="type"
                        v-else />
        </template>

      </ExpandCascader>
    </el-tooltip>
    <el-button @click="change"
               v-if="useLayerStatus"
               class="cuifont icon_dataset_add_layer"
               type="mini"
               style="font-size:14px;margin-left:10px;padding: 7px;"></el-button>
    <el-select v-if="!useLayerStatus"
               v-loading='datasetLayerSelectLoading'
               v-model="datasetLayerId"
               @input="$emit('input', $event)"
               @change="onLayerChange"
               :placeholder="placeholder"
               clearable
               style="margin-left:5px;width: 200px;">
      <el-option v-for="(item,index) in layerTempList"
                 :label="item.name"
                 :key="index"
                 :value="item.id">
      </el-option>
    </el-select>
  </div>
</template>
<script>
// import { getDictDataList } from '@/utils'
import CascaderNode from './components/cascader-node'
import ExpandCascader from '@/components/expand-cascader'
export default {
  name: 'SelectDatasetGroup',
  components: {
    CascaderNode,
    ExpandCascader
  },
  data () {
    return {
      datasetSelectLoading: false,
      options: [],
      datasetList: [],
      value: [],
      layerList: [],
      useLayerStatus: true,
      datasetLayerId: '',
      datasetLayerSelectLoading: false
    }
  },
  created () {
    this.init()
  },
  props: {
    placeholder: String,
    width: String,
    defaultValue: String,
    selectDatasetLayerId: {
      type: String,
      default: null
    },
    disabled: {
      type: Boolean,
      default: false
    },
    isBot: {
      type: Boolean,
      default: false
    },
    dataInfo: {
      type: Object,
      default: () => {
        return {}
      }
    },
    widthLength: {
      type: String

    },
    type: String
  },
  watch: {
    defaultValue (val) {
      if (!val) this.value = []
    },
    selectDatasetLayerId: {
      handler: function (val) {
        if (val) {
          this.useLayerStatus = false
          this.datasetLayerId = val
        } else {
          this.datasetLayerId = ''
        }
      },
      deep: true
    },
    value: {
      handler (val) {
        const { get, set } = this._
        let item = this.datasetList.find(e => e.id === val[1])
        set(item, 'datasetStatus', get(item, 'status'))
        this.$emit('onValueChange', { ...item, status: true })
      },
      deep: true
    }

  },
  computed: {
    datasetNameTooltip () {
      try {
        return this.datasetList.find(item => item.id === this.value[1]).description
      } catch (error) {
        return null
      }
    },
    layerTempList () {
      try {
        if (this.value[1]) {
          return this._.filter(this.layerList, { 'datasetId': this.value[1] })
        }
      } catch (error) {
        return []
      }
    }
  },
  methods: {
    init () {
      // if (this.selectDatasetLayerId) {
      //   this.useLayerStatus = false
      //   this.datasetLayerId = this.selectDatasetLayerId
      // }
      if (this.selectDatasetLayerId) {
        let temp = this.selectDatasetLayerId
        this.selectDatasetLayerId = null
        this.$nextTick(() => { this.selectDatasetLayerId = temp })
      }
      this.datasetSelectLoading = true
      this.datasetLayerSelectLoading = true
      const internal = this.isBot ? this.$store.state.bot.businessType === 'MSPbots Internal' : this.dataInfo.businessType === 'MSPbots Internal'
      const params = {
        resourceType:internal?150:5,
        showAllIntegration: false,
        internal: internal
      }
      this.$interface.reports.getReportDatasetListApi(params)
        .then(({ data: res }) => {
          this.datasetSelectLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.getLayerList()
          let tempList = []
          this.datasetList = res.data
          res.data.map(e => {
            tempList.push(e)
          })
          let groupList = []
          let groupChildren = []
          this.value = []
          this.options = []

          tempList.forEach(item => {
            if (item.id === this.defaultValue && this.value.length === 0) {
              this.value[0] = item.integration[0]
              this.value[1] = item.id
              // this.value[2] = item.status
            }
            item.integration.forEach(integration => {
              if (groupList.indexOf(integration) === -1) {
                groupList.push(integration)
                groupChildren[integration] = []
              }
              groupChildren[integration].push({
                value: item.id,
                label: item.name,
                datasetStatus: item.status,
                description: item.description
              })
            }
            )
          })
          groupList.forEach(element => {
            this.options.push({
              value: element,
              label: element,
              children: groupChildren[element]
            })
          })

          this.$forceUpdate()
        })
        .catch(() => {
          this.datasetSelectLoading = false
          this.datasetLayerSelectLoading = false
        })
    },
    onSelectChange (val) {
      if(!val) {
        this.value = []
      }
      let item = this.datasetList.find(e => e.id === this.value[1])
      if (item) item.datasetStatus = item.status
      this.useLayerStatus = true
      this.datasetLayerId = null
      if (item) {
        this.$emit('onSelectChange', { ...item, status: true })
      } else {
        this.$emit('onSelectChange', {})
      }
      this.$forceUpdate()
    },
    filterMethod (node, keyword) {
      return node.text.toLowerCase().indexOf(keyword.toLowerCase()) !== -1
    },
    change () {
      this.useLayerStatus = !this.useLayerStatus
    },
    onLayerChange () {
      if (!this.datasetLayerId) {
        this.useLayerStatus = true
        this.datasetLayerId = null
      }
      let datasetItem = this.datasetList.find(e => e.id === this.value[1])
      let datasetLayerItem = this.layerList.find(e => e.id === this.datasetLayerId)
      if (datasetLayerItem) {
        this.$emit('onSelectChange', { id: datasetItem.id, name: datasetItem.name, datasetLayerId: datasetLayerItem.id, datasetLayerName: datasetLayerItem.name, status: false, datasetStatus: datasetItem.datasetStatus })
      } else {
        this.$emit('onSelectChange', { id: datasetItem.id, name: datasetItem.name, status: false, datasetStatus: datasetItem.datasetStatus })
      }
      this.$forceUpdate()
    },
    getLayerList () {
      this.datasetLayerSelectLoading = true
      this.$interface.reports.getDatasetLayerList().then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.layerList = res.data
        this.datasetLayerSelectLoading = false
        this.$forceUpdate()
      }).catch(() => { this.datasetLayerSelectLoading = false })
    },
    handleClear () {
      this.value = []
    }
  }
}
</script>
<style lang="scss">
.dataset_data_grounp {
  display: flex;
}
.dataset_data_grounp_cascader {
  .el-cascader-panel {
    > .el-scrollbar:nth-child(2) {
      .el-cascader-menu__wrap {
        li {
          // width: 250px;
        }
        .el-cascader-node {
          max-width: 600px;
          height: auto;
          line-height: inherit;
          padding-top: 8px;
          padding-bottom: 8px;
          .el-cascader-node__label {
            white-space: normal;
          }
        }
      }
    }
  }
}
.dataset_data_grounp_cascader {
  .el-cascader-panel {
    > .el-scrollbar:nth-child(1) {
      .el-cascader-menu__wrap {
        .el-cascader-node {
          .el-cascader-node__label {
            padding: 0 30px 0 10px;
          }
        }
      }
    }
  }
}
</style>
